package com.atguigu.day02;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Flink07_TransForm_Map {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据
//        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);
        DataStreamSource<String> streamSource = env.readTextFile("input/sensor.txt");

        //TODO 3.使用Map将读过来的数据转为WaterSensor
     /*   SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MapFunction<String, WaterSensor>() {

            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });*/

        SingleOutputStreamOperator<WaterSensor> map = streamSource.map(new MyRichMap());

        map.print();

        env.execute();
    }

    //自定义一个类继承富函数的抽象类
    public static class MyRichMap extends RichMapFunction<String, WaterSensor> {
        /**
         *  生命周期方法 在调用map之前最先被调用 每个并行度上调用一次
         *  通常用于做初始化操作，比如创建链接
         * @param parameters
         * @throws Exception
         */
        @Override
        public void open(Configuration parameters) throws Exception {
            System.out.println("open....");
        }

        /**
         * 生命周期方法 在调用map之后最后被调用 每个并行度上调用一次 特殊情况：在读文件时close每个并行度调用两次
         * 通常用于做关闭资源操作，比如关闭链接
         * @throws Exception
         */
        @Override
        public void close() throws Exception {
            System.out.println("close....");
        }


        @Override
        public WaterSensor map(String value) throws Exception {
            //通过运行时上下文对象可以获取到额外的元数据信息，或者一些状态
            System.out.println(getRuntimeContext().getTaskName());
            System.out.println(getRuntimeContext().getJobId());

            String[] split = value.split(",");
            return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
        }

    }

}
